from model.order import OrderDao, OrderItemDao
from model.address import AddressDao
from model.city import CityDao
from lib.validator import Validator
from lib.form import Form

from bson.dbref import DBRef
from bson.objectid import ObjectId
from flask import request
from flask_login import login_user, current_user
import time

from service import Service

class OrderService(Service):
    def __init__(self):
        self.dao = OrderDao()
        self.address_dao = AddressDao()
        self.city_dao = CityDao()
        
    def get_all_orders(self):
        orders = []

        _orders = self.dao.all()
        for _order in _orders:
            address = self.address_dao.find_one({'_id':_order.address['_id']})
            city = self.city_dao.find_one({'_id':address.city['_id']})
            orders.append({"name":_order.name, 
                          "description":_order.description, 
                          "street":address.street,
                          "city": "{0} {1} {2}".format(city.name, city.province, city.country),
                          "postcode":address.postcode})
        return orders


    def submit_order(self, inputs):
        # Submit address
        
        # Submit order
        if inputs['mode'] == 'edit':
            #order = order_dao.update_order(inputs['id, inputs['name, inputs['description)
            return None
        elif inputs['mode'] == 'new':
            city = self.city_dao.find_one({'name':inputs['city'], 'province':inputs['province'], 'country':inputs['country']})
            city_dbref = DBRef('cities', city._id )
            address_dict = {'street':inputs['street'], 'postcode':inputs['postcode'], 'city':city_dbref}
            address = self.address_dao.find_one(address_dict)

            _dict = {'name':inputs['name'],
                     'description': inputs['description']}
            
            if address is None:
                address_id = self.address_dao.save(address_dict)
                _dict['address'] = DBRef('addresses', address_id)
            else:
                _dict['address'] = DBRef('addresses', address._id)
                
            return self.dao.save(_dict)



class OrderValidator(Validator):
    def __init__(self):
        Validator.__init__(self)
              
        self.rules = {'title': { 
                                'required' : [None, True],
                                'minlength':[None, 1],
                                'maxlength':[None, 256]
                                }
        }

    
class OrderForm(Form):
    """ Submit user form
    """
    def __init__(self):
        """Only accept POST request
        """
        Form.__init__(self)
        self.validator = OrderValidator()
        
        if self.is_submitted():
            self.raw_inputs = self.get_raw_inputs()
            self.inputs = self.get_inputs(self.raw_inputs)
            self.errors = self.validator.validate(self.inputs)

    def get_inputs(self, raw_inputs):                
        """ Convert inputs type
        """
        return {'title': raw_inputs['title'],
                'user_id': raw_inputs['uid']
        }
        
    def has_error(self):
        return self.errors != []



class OrderItemService(Service):
    def __init__(self, order):
        self.dao = OrderItemDao()
        self.address_dao = AddressDao()
        self.city_dao = CityDao()
        self.order = order
        
    def get_order_items(self, order_ref):
        order_items = self.dao.all({'order':order_ref})
        for _order_item in order_items:
            item = self.item_dao.find_one({'_id':_order_item.item['_id']})
            order_items.append({"name":item.name, 
                          "description":item.description,
                          "price": item.price,
                          "quantity": _order_item.quantity})
        return order_items


    def submit_order_item(self, inputs):
        # Submit address
        
        # Submit order
        if inputs['mode'] == 'edit':
            #order = order_dao.update_order(inputs['id, inputs['name, inputs['description)
            return None
        elif inputs['mode'] == 'new':
            item = self.item_dao.find_one({'_id': ObjectId('items',inputs['iid'])})

            _dict = {'quantity':inputs['quantity'],
                     'order': DBRef('orders', self.order._id),
                     'item': DBRef('items', item._id)
                     }
                
            return self.dao.save(_dict)


    
class OrderItemValidator(Validator):
    def __init__(self):
        Validator.__init__(self)
              
        self.rules = {'quantity': { 
                                'required' : [None, True],
                                'numeric':[None, True],
                                'min':[None, 1],
                                'max':[None, 256]
                                }
        }
        
class OrderItemForm(Form):
    def __init__(self):
        """Only accept POST request
        """
        Form.__init__(self)
        self.validator = OrderItemValidator()
        
        if self.is_submitted():
            self.raw_inputs = self.get_raw_inputs()
            self.inputs = self.get_inputs(self.raw_inputs)
            self.errors = self.validator.validate(self.inputs)

    def get_inputs(self,raw_inputs):                
        """ Convert inputs type
        """
        quantity = int(raw_inputs['quantity'])
        return {'quantity': quantity,
               'user_id': raw_inputs['uid'],
               'item_id': raw_inputs['iid']
        }
        
    def has_error(self):
        return self.errors != []